from django.contrib.auth import authenticate
from rest_framework.request import Request
from rest_framework import generics, viewsets
from rest_framework.response import Response
from rest_framework.views import APIView

from User.Auth import TokenAuth
from User.models import SiteUser, Resource
from User.serializers import SiteUserRegisterSerializer, ResourceSerializer
from misaka.modelViewSet.withUserModelViewSet import withUserModelViewSet, ManagerOwnerViewSet
from misaka.permissions import isLogin, ManagerOwner


# Create your views here.
class RegisterView(generics.CreateAPIView):
    queryset = SiteUser.objects.all()
    serializer_class = SiteUserRegisterSerializer


class LoginView(APIView):
    def post(self, request: Request):
        data: dict = request.data
        username = data.get("username")
        password = data.get("password")
        user: SiteUser = authenticate(username=username, password=password)

        if user is None:
            return Response(
                "验证不通过请重试", status=201
            )

        return Response(
            {
                "token": TokenAuth.make_user_token(uid=user.id)
            }, status=200
        )


class Test(APIView):
    authentication_classes = [isLogin]
    permission_classes = [ManagerOwner]

    queryset = SiteUser

    def post(self, request: Request):
        user: SiteUser = request.user
        return Response({
            'result': f"进入成功, 你好{user.username}"
        })


class Test2(withUserModelViewSet, ManagerOwnerViewSet):
    queryset = Resource.objects.all()
    serializer_class = ResourceSerializer
    authentication_classes = [isLogin]
    permission_classes = [ManagerOwner]

    def get_obj_user(self, obj: Resource):
        return obj.user
